package cn.edu.ahu.aircondition.monitor.realtime;

import cn.edu.ahu.aircondition.monitor.realtime.domain.LongEvent;
import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.nio.ByteBuffer;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

@SpringBootApplication
public class Application implements CommandLineRunner {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

	public static void handleEvent(LongEvent event, long sequence, boolean endOfBatch) throws InterruptedException {
		Thread.sleep(1000);
		System.out.println(event.getValue());
	}

	public static void translate(LongEvent event, long sequence, ByteBuffer buffer) {
		event.set(buffer.getLong(0));
	}



	public void run(String... args) throws Exception {
		ThreadFactory threadFactory = new ThreadPoolTaskExecutor();
		Disruptor<LongEvent> disruptor = new Disruptor<>(new LongEventFactory(), 1024, threadFactory, ProducerType.MULTI, new BlockingWaitStrategy());
		disruptor.handleEventsWith(Application::handleEvent);
		disruptor.start();
		RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();
		ByteBuffer bb = ByteBuffer.allocate(8);


		ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);

		for (int i = 0; i < 10; i++) {
			fixedThreadPool.execute(() -> {
				for (long l = 0; true; l++)
				{
					bb.putLong(0, l);
					System.out.println("输入"+l);
					ringBuffer.publishEvent(Application::translate, bb);
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
            });
		}
	}
}
